#!/bin/bash
#
# A wrapper for doxygen to add missing basic functionality by adding
# the following additional parameters
# - The source root dir    [ originally the current dir where doxygen is run ]
# - The output root dir    [ originally specified in the config file ]
# - The config file        [ originally typically the last specified parameter ]
# Additional parameters are passed to doxygen directly

if [ $# -lt 3 ]; then
	echo "Usage: `basename "$0"` source_root output_root config_file [doxygen parameters]"
	echo "Note on the paths:"
	echo "       source_root can be relative to rundir or absolute"
	echo "       output_root can be relative to source_root or absolute, may not contain '!'"
	echo "       config_file can be relative to rundir or absolute"
	echo "       doxygen parameters may not specify the config file/source"
	echo ""
	echo "Not all three mandatory parametes given."
	exit 1
fi

# Adjust the source root dir
RUNDIR=`pwd`
SOURCEDIR=$1

# The config file can be specified relative to the run-dir
if [ "${3%%[^/]*}" = "/" ]; then
	CONF="$3"
else
	CONF="$RUNDIR/$3"
fi

OUTDIR=$2

# Create tmp file to hold stdout, remove file but keep it open via stream handle #3
# (will be removed after script ends, yeah RAII)
tmpfile=$(mktemp /tmp/doxywrap.XXXXXX)
exec 3>"$tmpfile"
rm "$tmpfile"

echo WRAPPER CALL $@
shift; shift; shift

# Fail fast if sed or doxygen failed. Ignore grep due to '|| true'.
set -eo pipefail

# Stream magic:
#   redirect doxygen's standard stream to the extra stream (1 -> 3)
#   redirect doxygen's error stream to the pipe (standard) stream (2 -> 1)
#   filter the standard stream that comes through the pipe with grep -v
#   now put the streams back where they belong pipe output to error stream (1 -> 2)
#   and the extra stream (standard out of doxygen) to standard out (3 -> 1)
cd "$SOURCEDIR" \
	&& ( \
		sed -e "s!^\(OUTPUT_DIRECTORY\s*=\s*\).*!\1$OUTDIR!" "${CONF}" \
		| doxygen $@ - 2>&1 1>&3 \
		| ( grep -v 'include/gul14/string_view.h:[0-9]\+: warning:' || true ) 1>&2 \
	) 3>&1
